package com.xxc.common.util

import org.springframework.core.io.ClassPathResource
import org.springframework.http.HttpHeaders
import org.springframework.http.HttpStatus
import org.springframework.http.MediaType
import org.springframework.http.ResponseEntity
import sun.management.resources.agent
import sun.misc.BASE64Encoder
import java.io.File
import java.net.URLEncoder
import java.nio.charset.Charset
import java.nio.file.Files
import java.nio.file.Paths

object FileUDUtil {

    /**
     * 处理下载文件时的文件名中文乱码问题，兼容浏览器
     * @param filename 源文件名
     * @param agent 浏览器的user-agent
     */
    fun resolveDownloadFileName(filename:String,agent: String):String{
        var filenameEncoder: String
        when {
            agent.contains("MSIE") -> {
                // IE浏览器
                filenameEncoder = URLEncoder.encode(filename, "utf-8")
                filenameEncoder = filenameEncoder.replace("+", " ")
            }
            agent.contains("Firefox") -> {
                // 火狐浏览器
                val base64Encoder = BASE64Encoder()
                filenameEncoder = "=?utf-8?B?" + base64Encoder.encode(filename.toByteArray(Charset.forName("utf-8"))) + "?="
            }
            else -> // 其它浏览器
                filenameEncoder = URLEncoder.encode(filename, "utf-8")
        }
        return filenameEncoder
    }

    /**
     * 将path的文件转换为ResponseEntity
     * @param path 文件所在文件夹路径
     * @param filename 文件名
     * @param agent 浏览器的user-agent
     */
    fun downloadFile(path:String, filename:String,agent:String):ResponseEntity<ByteArray> {
        // 获取目录下的资源
        val cpr = ClassPathResource(path+File.separatorChar + filename)
        // 获得请求头中的User-Agent
        // 根据不同的客户端进行不同的编码
        var filenameEncoder: String
        when {
            agent.contains("MSIE") -> {
                // IE浏览器
                filenameEncoder = URLEncoder.encode(filename, "utf-8")
                filenameEncoder = filenameEncoder.replace("+", " ")
            }
            agent.contains("Firefox") -> {
                // 火狐浏览器
                val base64Encoder = BASE64Encoder()
                filenameEncoder = "=?utf-8?B?" + base64Encoder.encode(filename.toByteArray(Charset.forName("utf-8"))) + "?="
            }
            else -> // 其它浏览器
                filenameEncoder = URLEncoder.encode(filename, "utf-8")
        }
        // 模板代码，装配ResponseEntity
        val input = cpr.inputStream
        val body: ByteArray = ByteArray(input.available())
        input.read(body)
        val headers = HttpHeaders()
        headers.contentType = MediaType.parseMediaType(Files.probeContentType(Paths.get(cpr.file.absolutePath)))
        // 让浏览器显示下载文件对话框
        headers.add("Content-Disposition", "attchement;filename=$filenameEncoder")
        val statusCode = HttpStatus.OK
        return ResponseEntity(body, headers, statusCode)
    }
}